package bbk.nfc;

import bbk.nfc.R;

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class ReadActivity extends Activity 
{
	public static final String TAG = "NFC_MAIN";
	TextView mTxt;
	NfcAdapter mNfcAdapter;
	PendingIntent mPendingIntent;
	IntentFilter[] mIntentFiltersArray;
	String[][] mTechListsArray;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate:" + savedInstanceState);
		setContentView(R.layout.activity_main);
		mTxt = (TextView) findViewById(R.id.text);
		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (mNfcAdapter == null)
		{
			Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		// Register callback
		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
		try
		{
			ndef.addDataType("*/*");
		}
		catch (MalformedMimeTypeException e)
		{
			throw new RuntimeException("fail", e);
		}
		mIntentFiltersArray = new IntentFilter[]{ ndef , };
		mTechListsArray = new String[][]{ new String[]{MifareUltralight.class.getName()},new String[]{MifareClassic.class.getName()} };
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Log.i(TAG, "onResume:" + getIntent().getAction());
		if(mNfcAdapter!=null)
			mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFiltersArray, mTechListsArray);
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()))
		{
			Log.i(TAG, "onResume 2:" + getIntent());
			String s = NfcRW.readNFC(getIntent(),this);
			mTxt.setText(s);
		}
	}
	
	public void onPause()
	{
		super.onPause();
		Log.i(TAG, "onPause");
		if(mNfcAdapter!=null)
			mNfcAdapter.disableForegroundDispatch(this);
	}
	
	@Override
	public void onNewIntent(Intent intent)
	{
		// onResume gets called after this to handle the intent
		super.onNewIntent(intent);
		Log.i(TAG, "onNewIntent:" + intent);
		setIntent(intent);
	}	
}
